package personalProfile;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Types;
import java.util.ArrayList;
import java.util.ResourceBundle;

import javax.swing.ImageIcon;

import managers.DBManager;
import managers.socialNetworkManagers.CacheManager;
import managers.socialNetworkManagers.SocialNetworkFeedbackManager;
import managers.socialNetworkManagers.SocialNetworkManager;
import spotGUI.personalProfileGUI.FamilyPanel;
import spotGUI.personalProfileGUI.ProfileUpdateLogger;
import spotGUI.personalProfileGUI.Updatable;
import utils.ImageUtils;
import utils.StackTracePrinter;

public class FamilyManager implements Updatable {

	public static final int FRIEND = 1;
	public static final int PARENT = 2;
	public static final int GRANDPARENT = 3;
	public static final int COUSIN = 4;
	public static final int UNCLE = 5;
	public static final int BOYFRIEND = 6;

	private int id;
	private ProfileUpdateLogger logger;
	private FamilyPanel view;

	private ArrayList<FamilyComponent> components;

	private ArrayList<FamilyComponent> pendingComponents;
	private ArrayList<FamilyComponent> pendingRemoveComponents;

	public FamilyManager (int id, ProfileUpdateLogger logger) {

		this.id = id;
		this.logger = logger;

		view = new FamilyPanel(this);

		components = new ArrayList<FamilyComponent>();
		new Thread () {
			public void run() {
				try {
					retrieveFamilyComponents(DBManager.getConnection());
				} catch (Exception e) {
					SocialNetworkManager.getSharedInstance().getFeedbackManager().updateStatus(
							ResourceBundle.getBundle("personalProfile.messages").getString("m.1"), SocialNetworkFeedbackManager.WARNING);
					StackTracePrinter.print(e);
				}

				for (int i = 0; i < components.size(); i++) {
					view.fillList(components.get(i));
				}
			}
		}.start();
	}


	private void retrieveFamilyComponents(Connection conn) throws SQLException, IOException {

		Statement stmt = conn.createStatement();
		String query = "select parentid, id, type, name from spotmessenger.FAMILYCOMPONENTS where id = "+id;
		ResultSet rs = stmt.executeQuery(query);

		while (rs.next()) {

			ImageIcon userImage = CacheManager.retrieveImage(CacheManager.formatFamilyPhotoName(rs.getInt(1)), null);
			if (userImage == null) {
				Statement stmt2 = conn.createStatement();
				ResultSet rs2 = stmt2.executeQuery ("select photo from spotmessenger.FAMILYCOMPONENTS where parentid = "+rs.getInt(1));
				rs2.next();
				if (rs2.getBytes(1) != null)
					CacheManager.saveImage(rs2.getBytes(1), CacheManager.formatFamilyPhotoName(rs.getInt(1)));
				userImage = ImageUtils.bytesToImage(rs2.getBytes(1), "/images/Icons/128x128/user.png");
				DBManager.closeResources(stmt2, rs2);
			}
			FamilyComponent component = new FamilyComponent(rs.getInt(3), rs.getString(4), userImage);
			components.add(component);
		}
		DBManager.closeResources(stmt, rs);
	}







	public class FamilyComponent {

		public int type;
		public String name;
		public ImageIcon photo;

		public FamilyComponent(int type, String name, ImageIcon photo) {
			super();
			this.type = type;
			this.name = name;
			this.photo = photo;
		}
	}


	public ArrayList<FamilyComponent> retrieveComponents () {
		return null;
	}

	public ArrayList<FamilyComponent> getFamilyComponents() {
		return components;
	}

	public FamilyPanel getPanel() {
		return view;
	}

	@Override
	public void edit() {
		view.makeEditable();
		pendingComponents = new ArrayList<FamilyComponent>();
		pendingRemoveComponents = new ArrayList<FamilyComponent>();

	}

	@Override
	public void update() {
		try {
			updateDB(DBManager.getConnection());
		} catch (SQLException e) {
			logger.addError(ResourceBundle.getBundle("personalProfile.messages").getString("l.1"));
			StackTracePrinter.print(e);
		}
	}

	private void updateDB(Connection conn) throws SQLException {

		conn.setAutoCommit(false);
		PreparedStatement stmt = conn.prepareStatement("insert into spotmessenger.FAMILYCOMPONENTS values (?, ?, ?, ?, ?)");

		for (int i = 0; i < pendingComponents.size(); i++) {
			FamilyComponent component = pendingComponents.get(i);
			stmt.setNull(1, Types.INTEGER);
			stmt.setInt(2, SocialNetworkManager.getSharedInstance().getUserId());
			stmt.setInt(3, component.type);
			stmt.setString(4, component.name);
			ImageUtils.imageToDB(component.photo, stmt, 5);
			stmt.addBatch();
		}
		for (int i = 0; i < pendingRemoveComponents.size(); i++) {
			stmt.addBatch("DELETE FROM spotmessenger.familycomponents WHERE id= "+id
					+" and name= '"+pendingRemoveComponents.get(i).name+"'");
		}
		stmt.executeBatch();

		conn.commit();
		conn.setAutoCommit(true);
		DBManager.closeResources(stmt, null);
	}


	public void addPendingComponent (int type, String name, String photoURL) {
		if (!name.equals("")) {
			ImageIcon photo = null;
			if (photoURL != null)
				photo = ImageUtils.resize(photoURL, 128, -1);
			FamilyComponent comp = new FamilyComponent(type, name, photo);
			pendingComponents.add(comp);
			view.fillList(comp);
			view.updateAllListLayouts();
		}
	}

	public void addPendingRemoveComponent (FamilyComponent component) {
		pendingRemoveComponents.add(component);
		view.updateAllListLayouts();
	}


	public FamilyPanel getView() {
		return view;
	}



}